//
//  videoDetailViewController.m
//  iNews
//
//  Created by lanou3g on 14-12-6.
//  Copyright (c) 2014年 张在青. All rights reserved.
//

#import "videoDetailViewController.h"
#import "videodetailview.h"
//#import <MediaPlayer/MediaPlayer.h>
#import "movieHandel.h"
#import "videoDteilModel.h"
#import "UIImage+ImageDown.h"
#import "videodetTableViewCell.h"
#import "AvdownLoad.h"
//#import "MobClick.h"

#import "mpPlayerView.h"
@interface videoDetailViewController ()<UITableViewDataSource,UITableViewDelegate>

{
    BOOL isFull;
}
//@property(nonatomic,retain)videodetailview *videtail;
@property(nonatomic,retain)mpPlayerView *movie;

@property(nonatomic,retain)UIView *Gview;
@end

@implementation videoDetailViewController

-(void)dealloc{
    
    [_movie release];
    [_videtail release];

    
    [_Gview release];
   
    [super dealloc ];
}

//归档编码
-(void)encodeWithCoder:(NSCoder *)aCoder{

    [aCoder encodeObject:self.videoTitle forKey:@"videotitle"];
    
}
//反归档编码

-(id)initWithCoder:(NSCoder *)aDecoder{

    self = [super init];
    
    if (self) {
        self.videoTitle = [aDecoder decodeObjectForKey:@"videotitle"];
    }
    
    return self;
   
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
        self.videtail = [[[videodetailview alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - 40)] autorelease];
        
        //初始化转动的view
        self.actvw = [[[UIActivityIndicatorView alloc] init] autorelease];
        self.actvw.center = self.videtail.vdtialView.center;
        
        [self.videtail addSubview:self.actvw];
        [self.actvw startAnimating];
        
     
        
    }
    return self;
}

-(void)loadView{

    self.view = self.videtail;

  
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //请求数据
    [[movieHandel movieshareData] requestMovieDetaildata:self.appendString];
    
    //设置代理
    self.videtail.vdTab.delegate = self;
    self.videtail.vdTab.dataSource = self;
    
    //添加toolbar
    
    UIToolbar *tobar = [[[UIToolbar alloc] initWithFrame:CGRectMake(0, [UIScreen mainScreen].bounds.size.height - 40, [UIScreen mainScreen].bounds.size.width, 40)] autorelease];
    
    tobar.barStyle = UIBarStyleBlackOpaque;
    
    tobar.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
    [self.view addSubview:tobar];
    
    
    //添加item
    UIBarButtonItem *one = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemRewind target:self action:@selector(backAction)] autorelease];
    UIBarButtonItem *two = [[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"laodDown.png"] style: UIBarButtonItemStyleDone target:self action:@selector(downloading)] autorelease];
    UIBarButtonItem *three = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:nil action:@selector(shareAction)] autorelease];
   
    //添加这个后可以自动适配空间
    UIBarButtonItem *flexItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil] autorelease];
    [tobar setItems:[NSArray arrayWithObjects: flexItem, one, flexItem, two, flexItem, three, flexItem, nil]];
    
    
    //给返回添加事件
    
    [self.videtail.button addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    
    //给firstButton添加事件
    [self.videtail.firstButton addTarget:self action:@selector(firstButtonAction) forControlEvents:UIControlEventTouchUpInside];
    
    //给seconbuttontian添加事件
    
    [self.videtail.secondbutton addTarget:self action:@selector(secondbuttonAction) forControlEvents:UIControlEventTouchUpInside];
    
  
    //给视频播放传入url
    [self playMovie:self.str_url];
    
    // 注册一个播放开始的通知
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(dobegin)
                                                 name: MPMoviePlayerLoadStateDidChangeNotification
                                               object:nil];


    
    // 添加观察者
    [[movieHandel movieshareData] addObserver:self forKeyPath:@"hostDetailArray" options: NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
    
    
    
   // [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayerFullAction) name:MPMoviePlayerWillEnterFullscreenNotification  object:nil];
    
    //检测是否进入全屏
  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayerFullAction) name:MPMoviePlayerDidEnterFullscreenNotification  object:nil];
    
    
    //检测将要推出全屏
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayerBack) name:MPMoviePlayerWillExitFullscreenNotification object:nil];
    
    
    
    
    
}

//观察者事件
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{

    
    
    if ([keyPath isEqualToString:@"hostDetailArray"]) {
        
        //判断数组元素是否为空
           if ([movieHandel movieshareData].hostDetailArray.count == 0 ) {
            
            [self.videtail.hafView bringSubviewToFront:self.videtail.dropview];

           
        }else{
            [self.videtail.hafView sendSubviewToBack:self.videtail.dropview];
         }
        
        [self.videtail.vdTab reloadData];
        
        
        [[movieHandel movieshareData] removeObserver:self forKeyPath:@"hostDetailArray"];
       }
    
  
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return [movieHandel movieshareData].hostDetailArray.count;


}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

   static NSString *cell_id = @"cell_id";
    
   videodetTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cell_id];
    
    if (cell == nil) {
        cell = [[videodetTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cell_id];
    }
    
    //用model类赋值
    videoDteilModel *vm =[movieHandel movieshareData].hostDetailArray[indexPath.row];
    
   //字符串替代
    NSString *sr = [vm.title stringByReplacingOccurrencesOfString:@"&quot;" withString:@"\""];
    
    cell.label.text = sr;
    cell.imagevw.image = [UIImage imageWithUrlString:vm.cover myBlock:^(UIImage *image) {
        cell.imagevw.image = image;
    }];
   
    
    
   if (vm.cover == nil) {
       cell.label.frame = CGRectMake(10, 0, [UIScreen mainScreen].bounds.size.width, cell.bounds.size.height);
   }
    return cell;
    
    
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{

    return 0.1;
}




-(void)backAction{

    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:MPMoviePlayerLoadStateDidChangeNotification object:nil];
    //退出模态
    [self dismissViewControllerAnimated:YES completion:nil];
    //关闭视频
    [self.movie stop];
    self.movie.contentURL = nil;
    
 
    
}

//分享事件
-(void)shareAction{
    
    

   [UMSocialSnsService presentSnsIconSheetView:self appKey:@"537bfc9456240b066602f82b" shareText:[NSString stringWithFormat:@"%@:%@",self.videoTitle,self.str_url] shareImage:nil  shareToSnsNames:@[UMShareToSina,UMShareToRenren] delegate:self];

}

//下载事件
-(void)downloading{


    UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"是否要下载" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    
    //[alter addButtonWithTitle:@"收藏"];
    
    [alter show];
    [alter release];

}

//弹框视图点击按钮时调用
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
  
    if (buttonIndex == 1) {
        
        //这里调用下载数据方法
        
        [[AvdownLoad Sharedown] downloadinginitWithRequest:self.str_url appendPath:self.videoTitle];
        
    }else{
    
    
    
    }


}

//第一个button事件把视频frame缩小
-(void)firstButtonAction{
    
      //改变hafview的frame;
        CGRect temp = self.videtail.hafView.frame;
        temp.origin = CGPointMake(0, 20);
        temp.size = CGSizeMake([UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - 20 - 40);
        self.videtail.hafView.frame = temp;
        
        //改变vdtab的frame;
        CGRect temp1 = self.videtail.vdTab.frame;
        temp1.size.height = [UIScreen mainScreen].bounds.size.height - 20 - 40;
        self.videtail.vdTab.frame = temp1;
        
    
    
    [UIView animateWithDuration:1 animations:^{
        
        //改变视频视图的frame
        [self.videtail.vdtialView setFrame:CGRectMake([UIScreen mainScreen].bounds.size.width - 150, [UIScreen mainScreen].bounds.size.height - 140, 150, 100)];
        //使视频的view适应
        [self.movie.view setFrame:self.videtail.vdtialView.bounds];
    }];
    
      
        [self.videtail bringSubviewToFront:self.videtail.vdtialView];

        //把返回的button置后
        [self.videtail sendSubviewToBack:self.videtail.button];
        
       //把第二个button提前
       self.videtail.secondbutton.hidden = NO;
       self.videtail.firstButton.hidden = YES;
        //把返回的button置后
        [self.videtail sendSubviewToBack:self.videtail.button];
    
    
       //初始化一个手势view
    self.Gview = [[[UIView alloc] initWithFrame:self.movie.view.bounds] autorelease];
    self.Gview.alpha = 0.1;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    [self.Gview addGestureRecognizer:tap];
    
    [self.movie.view addSubview:self.Gview];
    
    
    
}


//响应第二个button事件返回视频原farme
-(void)secondbuttonAction{
    
    [self.videtail.vdtialView setFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 260)];
    [self.movie.view setFrame:self.videtail.vdtialView.bounds];
    
    [self.videtail.hafView setFrame:CGRectMake(0, CGRectGetMaxY(self.videtail.vdtialView.frame),[UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height -CGRectGetHeight(self.videtail.vdtialView.frame) - 40)];
    
    //将第firstButton提前
       self.videtail.secondbutton.hidden = YES;
       self.videtail.firstButton.hidden = NO;
    
    //把返回button提前
    [self.videtail bringSubviewToFront:self.videtail.button];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    //先让视频停止
    [self.movie stop];
    
    [self.actvw startAnimating];
    //点击cell的时候更换视频
    videoDteilModel *vm = [movieHandel movieshareData].hostDetailArray[indexPath.row];
     self.str_url = vm.mp4_url;
     self.videoTitle = vm.title;
    //改变当前的url
    self.movie.contentURL = [NSURL URLWithString:self.str_url];
    [self secondbuttonAction];
    [self.movie play]; 

   
    
}

-(void)playMovie:(NSString *)fileName{
    
   
    NSURL *url = [NSURL URLWithString:fileName];
    //视频播放对象
    self.movie = [[[mpPlayerView alloc] initWithContentURL:url] autorelease];     //视频控制风格
    //self.movie.controlStyle =  MPMovieControlStyleNone;
 
    
    
    self.movie.controlStyle =  MPMovieControlStyleDefault;
    [self.movie.view setFrame:self.videtail.vdtialView.bounds];
    //视频缩放模式
    self.movie.scalingMode =  MPMovieScalingModeAspectFill;
    
    //视频重复模式
    //self.movie.repeatMode = MPMovieRepeatModeOne;
    [self.videtail.vdtialView addSubview:self.movie.view];
    
    [self.movie play];
    
}

#pragma mark --视频播放结束委托

/*
 @method 当视频播放完毕释放对象
 */
//
-(void)dobegin{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name: MPMoviePlayerLoadStateDidChangeNotification object:nil];
    
  [self.actvw stopAnimating];
    

    
}


//屏幕旋转
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(BOOL)shouldAutorotate
{
    return NO;
}

-(NSUInteger)supportedInterfaceOrientations
{
    if (isFull) {
        return UIInterfaceOrientationMaskLandscapeRight;
    }else {
    
       return UIInterfaceOrientationMaskPortrait;
    }

 
}


//全屏时调用的方法
-(void)moviePlayerFullAction{
    
    
    isFull = YES;
    [self supportedInterfaceOrientations];
    
    [[NSNotificationCenter defaultCenter]removeObserver:self name:MPMoviePlayerDidEnterFullscreenNotification object:nil];

    
    
}


//返回时再改为竖屏
-(void)moviePlayerBack{

    isFull = NO;

[[NSNotificationCenter defaultCenter]removeObserver:self name:MPMoviePlayerWillExitFullscreenNotification object:nil];
    
}



//手势点击方法
-(void)tapAction:(UITapGestureRecognizer *)sender{

    if (sender.state == UIGestureRecognizerStateEnded ) {
        
         [self secondbuttonAction];
    }
    
    [self.Gview removeFromSuperview];
   
}



@end
